var express = require('express');
const Account = require('../model/account');
const jwt = require('jsonwebtoken')
var router = express.Router();
var svgCaptcha = require('svg-captcha')

/* GET users listing. */
const serct = '_wz824_'

//获取验证码
router.get('/captcha', function (req, res) {
    var captcha = svgCaptcha.create({
      ignoreChars: '0o1l',
      noise: 2,
      color: true
    });
    req.session.captcha = captcha.text.toLowerCase();
    console.log(req.session)
    /*res.type('svg');
    res.status(200).send(captcha.data);*/
    res.type('svg');
    res.send(captcha.data)
  });



router.post('/login',async function(req, res) {
    console.log(req.body)
    let account;
    try {
        account = await Account.find({userId:req.body.userId})
    } catch (error) {
        res.send({
            status:1,
            message:error
        })
        return
    }
    console.log(req.body.userId)
    if(account.length>0){
        if(account[0].password == req.body.password){
            res.send(
                {
                    status:0,
                    token:jwt.sign({userId:account[0].userId},serct,{expiresIn:'200h'}),
                    message:'登陆成功'
                }
            )
            return
        }else{
            res.send({
                status:1,
                message:'密码错误'
            })
            return
        }
    }
    res.send({
        status:1,
        message:'用户不存在'
    });
    return
});


router.post('/getAccount',async function(req, res, next) {
    if(await (await Account.find({userId:req.body.userId})).length>0){
        res.send({
            status:1,
            message:'用户名已存在'
        });
        return;
    }
    let newAccount = {};
    newAccount.userId = req.body.userId
    newAccount.password = req.body.password
    newAccount.addDate = new Date()
    if(req.body.captcha!==req.session.captcha) {
        console.log(req.body.captcha,req.session.captcha)
        console.log("$$$", req.session)
        return res.send({code: 1, message: '验证码不正确请点击刷新验证码'})
    }
    // 删除保存的验证码
    delete req.session.captcha

    await Account.create(newAccount,function(err){
        if(err){
            res.send({
                status:1,
                message:'注册失败'
            });
        }else{
            res.send({
                status:0,
                message:'注册成功'
            });
        }
    })

});
module.exports = router;
